<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="getTitle"
    width="35%"
    @ok="handleSubmit"
    :maskClosable="false"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '@/components/Form';
  import { formSchema } from './api-interface';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { CreateInterfaceParams, UpdateInterfaceParams } from '@/api/system/model/systemModel';

  import { addInterface, updateInterface } from '@/api/system/interfaces';
  import { getDictionaryList } from '@/api/system/dictionary';

  import { useMessage } from '@/hooks/web/useMessage';
  import { useI18n } from '@/hooks/web/useI18n';

  const { createMessage } = useMessage();

  defineOptions({ name: 'InterfaceModal' });

  const emit = defineEmits(['success', 'register']);

  const isUpdate = ref(true);
  let interfaceId: Number;

  const [registerForm, { resetFields, setFieldsValue, validate, updateSchema }] = useForm({
    labelWidth: 100,
    schemas: formSchema,
    showActionButtonGroup: false,
    baseColProps: { lg: 24 },
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
    interfaceId = data.record?.id;

    const treeData = await getDictionaryList({ parent_id: 19 });
    // console.log(treeData.items);
    updateSchema({
      field: 'class_id',
      componentProps: { treeData: treeData['items'] },
    });

    let httpMethod: any = window.localStorage.getItem('httpMethod');
    if (!httpMethod) {
      const { items } = await getDictionaryList({ parent_id: 28 });
      window.localStorage.setItem('httpMethod', JSON.stringify(items));
      httpMethod = items;
    } else {
      httpMethod = JSON.parse(httpMethod);
    }

    updateSchema({
      field: 'method',
      componentProps: { treeData: httpMethod },
    });

    if (unref(isUpdate)) {
      setFieldsValue({
        ...data.record,
      });
    }
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

  async function handleSubmit() {
    try {
      const { t } = useI18n();
      const values = await validate();
      setModalProps({ confirmLoading: true });
      // TODO custom api
      if (unref(isUpdate)) {
        let params: UpdateInterfaceParams = {
          name: values['name'],
          url: values['url'],
          description: values['description'],
          class_id: values['class_id'],
          method: values['method'],
          perms_code: values['perms_code'],
        };
        const { code, message } = await updateInterface(interfaceId, params);
        if (code == 0) {
          createMessage.success(t('sys.api.updateSuccess'), 1, () => {
            closeModal();
            emit('success');
          });
        } else {
          createMessage.error(message);
        }
      } else {
        let params: CreateInterfaceParams = {
          name: values['name'],
          url: values['url'],
          description: values['description'],
          class_id: values['class_id'],
          method: values['method'],
          perms_code: values['perms_code'],
        };
        const { code, message } = await addInterface(params);
        if (code == 0) {
          createMessage.success(t('sys.api.createSuccess'), 1, () => {
            closeModal();
            emit('success');
          });
        } else {
          createMessage.error(message);
        }
      }
    } catch (error) {
      console.log(error);
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>

<style lang="less">
  .ant-form {
    margin-right: 25px;
  }
</style>
